package com.practice.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileIO {

	private static final String END_LINE = System.getProperty("line.separator");
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
	}
	
	public static List<String> readLine() {
		File inputFile = new File("E:\\Temporary\\File report.txt");
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		List<String> lines = new ArrayList<>();
		try {
			fileReader = new FileReader(inputFile);
			bufferedReader = new BufferedReader(fileReader);
			
			Pattern pattern = Pattern.compile("W:\\\\GSA\\\\MTP\\\\(source|work)\\\\(?<ID>\\d+)\\\\.+\\[.+\\]");
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				Matcher matcher = pattern.matcher(line);
				if (matcher.matches()) {
					System.out.println(line);
					System.out.println(matcher.group("ID"));
				}
				lines.add(line);
			}
		} catch (IOException ex) {
			printException(ex);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					printException(ex);
				}
			}
			
			if (fileReader != null) {
				try {
					fileReader.close();
				} catch (IOException ex) {
					printException(ex);
				}
			}
		}
		return lines;
	}
	
	public static void writeLine(List<String> lines) {
		File outputFile = new File("E:\\Temporary\\Result.txt");
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			fileWriter = new FileWriter(outputFile);
			bufferedWriter = new BufferedWriter(fileWriter);
			
			for (String line : lines) {
				bufferedWriter.write(line);
				bufferedWriter.write(END_LINE);
			}
		} catch (IOException ex) {
			printException(ex);
		} finally {
			if (bufferedWriter != null) {
				try {
					bufferedWriter.close();		
				} catch (IOException ex) {
					printException(ex);
				}
			}
			
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException ex) {
					printException(ex);
				}
			}
		}
	}
	
	public static void println(String str) {
		System.out.println(str);
	}
	
	public static void printException(Throwable ex) {
		System.out.println(ex.getMessage());
		System.out.println(ex.getStackTrace());
	}
}
